import { Document, Page, Text, View, Font } from '@react-pdf/renderer';
import { pdfStyle } from './pdfStyle';
import { PdfComparisonSection } from '../cmpInfo/CmpInfo';
import Watermark from './Watermark';

// 类型定义
interface PDFProps {
  generateDate: string;
  wmSwitch: boolean;
}

// 注册字体
Font.register({
  family: 'SourceHan',
  fonts: [
    {
      src: '/fonts/SourceHanSansCN-Regular.otf',
      fontWeight: 'normal',
    },
    {
      src: '/fonts/SourceHanSansCN-Bold.otf', // 粗体字体
      fontWeight: 'bold',
    }
  ],
});

const StoreReportPDF = ({ generateDate, wmSwitch }: PDFProps) => (
  <Document>
    <Page size="A4" style={pdfStyle.page}>

      {wmSwitch && <Watermark />}

      <View style={pdfStyle.container}>
        <Text style={pdfStyle.title}>门店对比分析报告</Text>
        <Text style={pdfStyle.date}>生成时间：{generateDate}</Text>

        {/* 对比分析组件 */}
        <PdfComparisonSection />

        {/* 智能报告 */}
        <View style={pdfStyle.aiContainer}>
          <Text style={pdfStyle.aiText}>
            {(() => {
              const content = JSON.parse(
                sessionStorage.getItem('store_analysis_report') || '{}'
              ).content || '';

              // 核心换行处理
              const maxCharsPerLine = 41; // 每行最多字符个数
              return content
                .replace(/([。！？])/g, '$1\n') // 标点后换行
                .split('\n')    // 分割段落
                .map((line: string | any[]) => {
                  // 按字数分割长行
                  const chunks = [];
                  for (let i = 0; i < line.length; i += maxCharsPerLine) {
                    chunks.push(line.slice(i, i + maxCharsPerLine));
                  }
                  return chunks.join('\n');
                })
                .join('\n');

            })()}
          </Text>
        </View>

      </View>
    </Page>
  </Document>
);

export default StoreReportPDF;